var needle = require('needle');
var path = require('path');
var event = require('../../core/event');
var config = require('../../core/config');
var notify = require('../notify/ui');
var util = require('../../util/index');
var Log = require('../../util/logger');
var io = require('../io/ui');

var ret = {
	init: function(){
		if(this.inited){
			return;
		}

		event.bind(event.events.file.upload, 'upload', this);
		event.bind(event.events.dialog.upload2, 'upload', this);
		this.inited = true;
	},

	onEvent: function (e, param) {
		if(e == event.events.file.upload){
			if(!config.getVal(config.ITEM.SID)){
				notify.addNotify({
					msg: config.i18n('tip07')
				});
				return true;
			}
			var note = require('../note/manager');
			this.chart = note.getNote('main');
			this.dialog = null;
			if(!this.chart){
				return true;  //no tip
			}
			//检查两个id
			var sid = util.getJsonChainValue(this.chart, 'meta.song.id');
			var cid = util.getJsonChainValue(this.chart, 'meta.id');
			if(!sid || !cid){
				this.dialog = require('./online');
				this.dialog.setManager(this);
				this.dialog.init();
				this.dialog.show();
				return true;
			}
			//2个id都存在才进入上传dialog
			this._toUpload();

			return true;
		}else if(e == event.events.dialog.upload2){
			if(!config.getVal(config.ITEM.SID)){
				notify.addNotify({
					msg: config.i18n('tip07')
				});
				return true;
			}
			var self = this;
			io.getAny().then(function(file){
				if(!file){
					return;
				}
				var ext = path.extname(file);
				if(!(ext == ".osu" || ext == ".tja")){
					return;
				}
				var dialog = require('./dialog_osu');
				dialog.setManager(self);
				dialog.init();
				dialog.show(file, ext);
			});
			return true;
		}
	},

	doRequest: function(url, data, method){
		method = method || 'get';
		var defer = Promise.defer();
		needle.request(method, url, data, {proxy:config.getVal(config.ITEM.PROXY)}, function(err, resp) {
			var ret = null;

			if(!err && resp.statusCode == 200){
				ret = JSON.parse(resp.body);
				//统一处理一些返回码
				if(ret.code == -1000){
					config.clearLogin();
					notify.addNotify({
						msg: config.i18n("tip07")
					});
					event.trigger(event.events.dialog.user);
				}
			}else if(resp){
				Log.e(err);
				Log.e("http code:"+resp.statusCode)
			}else{
				Log.e(err);
			}
			defer.resolve(ret);
		});

		return defer.promise;
	},

	_getChart: function() {
		return this.chart;
	},

	/**
	 * page id换Chart内容
	 * @param pid
	 * @returns {*}
	 * @private
	 */
	_getOnlineChartInfo: function(pid) {
		var url = config.getServer()+"/cgi/query?"+config.getHttpSession()+"&type=2&cid="+pid;
		return this.doRequest(url, null);
	},

	_getOnlineSongInfo: function(pid) {
		var url = config.getServer()+"/cgi/query?"+config.getHttpSession()+"&type=1&sid="+pid;
		return this.doRequest(url, null);
	},

	/**
	 * 同时创建song和Chart页
	 * @param conf
	 * @returns {*}
	 * @private
	 */
	_createOnlineChart: function(conf) {
		var url = config.getServer()+"/page/create_editor?"+config.getHttpSession();
		return this.doRequest(url, conf, 'post');
	},
	
	_getUploadSign: function(conf) {
		var url = config.getServer()+"/upload/chart?"+config.getHttpSession();
		return this.doRequest(url, conf, 'post');
	},

	_sendUploadConfirm: function(conf) {
		var url = config.getServer() + "/upload/chart_confirm?"+config.getHttpSession();
		return this.doRequest(url, conf, 'post');
	},

	_uploadToCDN: function(conf) {
		var url = 'http://v0.api.upyun.com/ma-chart';
		var defer = Promise.defer();

		var opt = {
			open_timeout: 0,
			multipart: true,
			proxy:config.getVal(config.ITEM.PROXY)
		};

		needle.post(url, conf, opt, function(err, resp) {
			var ret = null;
			if(!err && resp.body){
				ret = JSON.parse(resp.body);
			}else if(resp){
				Log.e("cdn code:"+resp.statusCode+" msg:"+err);
			}else{
				Log.e("cdn failed, timeout");
			}
			defer.resolve(ret);
		});
		return defer.promise;
	},

	_toUpload: function(){
		this.dialog = require('./dialog');
		this.dialog.setManager(this);
		this.dialog.init();
		this.dialog.show();
	}
};

module.exports = ret;